<template>
	<view>
		<view class="user-section">
			<image class="bg" src="/static/user-bg.jpg"></image>
			<text class="bg-upload-btn yticon icon-paizhao" @click="chooseImage('bg')"></text>
			<view class="portrait-box">
				<image class="portrait" :src="userInfo.icon || '/static/missing-face.png'"></image>
				<text class="pt-upload-btn yticon icon-paizhao" @click="goToAvatarPage"></text>
			</view>
		</view>
		
		<!-- 个人信息表单 -->
		<view class="info-form">
			<view class="form-item">
				<view class="label">用户名</view>
				<view class="content">
					<text>{{userInfo.username}}</text>
				</view>
			</view>
			<view class="form-item">
				<view class="label">昵称</view>
				<view class="content">
					<input type="text" v-model="formData.nickname" placeholder="请输入昵称" />
				</view>
			</view>
			<view class="form-item">
				<view class="label">手机号码</view>
				<view class="content">
					<input type="number" v-model="formData.phone" placeholder="请输入手机号码" maxlength="11" />
				</view>
			</view>
			<view class="form-item">
				<view class="label">性别</view>
				<view class="content">
					<picker @change="bindGenderChange" :value="genderIndex" :range="genderOptions" range-key="text">
						<view class="uni-input">{{getGenderText(formData.gender)}}</view>
					</picker>
				</view>
				<text class="yticon icon-you"></text>
			</view>
			<view class="form-item">
				<view class="label">生日</view>
				<view class="content">
					<picker mode="date" :value="formData.birthday" @change="bindDateChange">
						<view class="picker-content">
							{{formData.birthday || '请选择生日'}}
						</view>
					</picker>
				</view>
				<text class="yticon icon-you"></text>
			</view>
			<view class="form-item">
				<view class="label">所在城市</view>
				<view class="content">
					<view class="picker-content" @click="showCityPicker">
						<text v-if="formData.province || formData.city || formData.area">
							{{formData.province}}{{formData.city}}{{formData.area}}
						</text>
						<text v-else>请选择所在地区</text>
					</view>
				</view>
				<text class="yticon icon-you"></text>
			</view>
			<view class="form-item">
				<view class="label">职业</view>
				<view class="content">
					<input type="text" v-model="formData.job" placeholder="请输入职业" />
				</view>
			</view>
			<view class="form-item textarea-item">
				<view class="label">个性签名</view>
				<view class="content">
					<textarea v-model="formData.signature" placeholder="请输入个性签名" />
				</view>
			</view>
			<view class="form-item">
				<view class="label">会员积分</view>
				<view class="content">
					<text>{{userInfo.integration || 0}}</text>
				</view>
			</view>
			<view class="form-item">
				<view class="label">成长值</view>
				<view class="content">
					<text>{{userInfo.growth || 0}}</text>
				</view>
			</view>
		</view>
		
		<view class="save-btn-box">
			<button class="save-btn" @click="saveUserInfo">保存</button>
		</view>
		
		<!-- 省市区选择器 -->
		<mpvue-city-picker
			ref="mpvueCityPicker"
			:pickerValueDefault="cityPickerValueDefault"
			@onConfirm="onConfirmCity"
		></mpvue-city-picker>
	</view>
</template>

<script>
	import {  
	    mapState,  
	    mapMutations  
	} from 'vuex';
	import { API_BASE_URL } from '@/utils/appConfig.js';
	import { memberInfo, updateMemberInfo, uploadAvatar } from '@/api/member.js';
	import mpvueCityPicker from '@/components/mpvue-citypicker/mpvueCityPicker.vue';
	
	export default {
		components: {
			mpvueCityPicker
		},
		data() {
			return {
				formData: {
					username: '',
					nickname: '',
					phone: '',
					gender: 1, // 默认性别为男
					birthday: '',
					province: '',
					city: '',
					area: '',
					job: '',
					signature: '',
					icon: ''
				},
				isSubmitting: false,
				genderOptions: [
					{ text: '男', value: 1 },
					{ text: '女', value: 2 }
				],
				cityPickerValueDefault: [0, 0, 0],
				themeColor: '#007AFF',
				cityPickerValue: [0, 0, 0],
				pickerValueArray: [],
				isCityPickerVisible: false,
				genderIndex: 0
			};
		},
		computed:{
			...mapState(['userInfo']),
		},
		onLoad() {
			// 加载用户信息到表单
			console.log('页面加载，开始获取用户信息');
			this.loadUserInfo();
		},
		methods: {
			...mapMutations(['updateUserInfo']),
			
			// 获取最新的用户信息
			loadUserInfo() {
				uni.showLoading({
					title: '加载中...'
				});
				
				memberInfo().then(res => {
					uni.hideLoading();
					console.log('获取的用户信息:', res);
					
					// 兼容两种API响应格式: {errno: 0, data: ...} 或 {code: 200, data: ...}
					if((res.errno === 0 || res.code === 200) && res.data) {
						// 更新Vuex中的用户信息
						this.updateUserInfo(res.data);
						// 初始化表单数据
						this.initFormData();
					} else {
						uni.showToast({
							icon: 'none',
							title: res.errmsg || res.message || '获取用户信息失败'
						});
					}
				}).catch(err => {
					uni.hideLoading();
					console.error('获取用户信息失败', err);
					uni.showToast({
						icon: 'none',
						title: '获取用户信息失败，请重试'
					});
				});
			},
			
			initFormData() {
				const userInfo = this.userInfo;
				console.log('初始化表单数据，用户信息:', userInfo);
				
				this.formData.username = userInfo.username || '';
				this.formData.nickname = userInfo.nickname || '';
				this.formData.phone = userInfo.phone || ''; // 手机号
				this.formData.gender = userInfo.gender || 1;
				
				// 设置性别选择器索引
				const genderIndex = this.genderOptions.findIndex(item => item.value === this.formData.gender);
				this.genderIndex = genderIndex >= 0 ? genderIndex : 0;
				
				// 处理生日数据
				if (userInfo.birthday) {
					// 如果是时间戳格式
					if (typeof userInfo.birthday === 'number') {
						const date = new Date(userInfo.birthday);
						this.formData.birthday = this.formatDate(date);
					} else if (typeof userInfo.birthday === 'string') {
						// 如果是字符串，尝试格式化
						this.formData.birthday = this.formatDate(userInfo.birthday);
					} else {
						this.formData.birthday = '';
					}
				} else {
					this.formData.birthday = '';
				}
				
				// 职业和个性签名初始化
				this.formData.job = userInfo.job || '';
				// 处理个性签名 - 兼容不同的字段名
				this.formData.signature = userInfo.signature || userInfo.personalizedSignature || '';
				this.formData.icon = userInfo.icon || '';
				
				// 处理城市信息
				if(userInfo.city) {
					// 从城市信息中提取省市区
					const cityInfo = this.extractCityInfo(userInfo.city);
					this.formData.province = cityInfo.province;
					this.formData.city = cityInfo.city;
					this.formData.area = cityInfo.area;
				}
				
				console.log('表单数据初始化完成:', this.formData);
			},
			
			// 提取城市信息
			extractCityInfo(cityStr) {
				// 默认结果
				const result = {
					province: '',
					city: '',
					area: ''
				};
				
				if (!cityStr || typeof cityStr !== 'string') {
					return result;
				}
				
				// 尝试从城市字符串中提取省市区信息
				// 这里使用简单的模式匹配，实际应用可能需要更复杂的处理
				
				// 常见的省级行政区后缀
				const provincePattern = /(.*?(省|自治区|直辖市|特别行政区))/;
				// 常见的市级行政区后缀
				const cityPattern = /(.*?(市|地区|自治州))/;
				// 常见的区县级行政区后缀
				const areaPattern = /(.*?(区|县|市|旗))/;
				
				let remainingStr = cityStr;
				
				// 提取省份
				const provinceMatch = remainingStr.match(provincePattern);
				if (provinceMatch && provinceMatch[1]) {
					result.province = provinceMatch[1];
					remainingStr = remainingStr.substring(provinceMatch[1].length);
				}
				
				// 提取城市
				const cityMatch = remainingStr.match(cityPattern);
				if (cityMatch && cityMatch[1]) {
					result.city = cityMatch[1];
					remainingStr = remainingStr.substring(cityMatch[1].length);
				}
				
				// 提取区/县
				const areaMatch = remainingStr.match(areaPattern);
				if (areaMatch && areaMatch[1]) {
					result.area = areaMatch[1];
					remainingStr = remainingStr.substring(areaMatch[1].length);
				}
				
				// 如果没有匹配出任何信息，则尝试简单分割
				if (!result.province && !result.city && !result.area) {
					if (cityStr.length <= 3) {
						// 如果总长度很短，可能只是城市名
						result.city = cityStr;
					} else if (cityStr.length <= 6) {
						// 可能是省市
						result.province = cityStr.substring(0, 2);
						result.city = cityStr.substring(2);
					} else {
						// 尝试均分为省市区
						const partLength = Math.floor(cityStr.length / 3);
						result.province = cityStr.substring(0, partLength);
						result.city = cityStr.substring(partLength, partLength * 2);
						result.area = cityStr.substring(partLength * 2);
					}
				}
				
				console.log('解析城市信息:', cityStr, '→', result);
				return result;
			},
			
			// 选择性别
			bindGenderChange(e) {
				const index = e.detail.value;
				this.formData.gender = this.genderOptions[index].value;
				this.genderIndex = index;
			},
			
			// 选择图片
			chooseImage(type) {
				if (type === 'avatar') {
					// 跳转到头像上传页面
					this.goToAvatarPage();
					return;
				}
				
				// 仅处理背景图上传
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0];
						if (type === 'bg') {
							// 背景图更新逻辑，这里简化处理
							uni.showToast({
								title: '背景图更新成功',
								icon: 'none'
							});
						}
					}
				});
			},
			
			// 显示城市选择器
			showCityPicker() {
				this.$refs.mpvueCityPicker.show();
			},
			
			// 城市选择器确认
			onConfirmCity(e) {
				this.formData.province = e.province.label || '';
				this.formData.city = e.city.label || '';
				this.formData.area = e.area.label || '';
			},
			
			// 保存用户信息
			saveUserInfo() {
				if(!this.formData.nickname){
					uni.showToast({
						icon: 'none',
						title: '昵称不能为空'
					});
					return;
				}
				
				if(!this.formData.phone){
					uni.showToast({
						icon: 'none',
						title: '手机号不能为空'
					});
					return;
				}
				
				if(!/^1\d{10}$/.test(this.formData.phone)){
					uni.showToast({
						icon: 'none',
						title: '手机号格式不正确'
					});
					return;
				}
				
				this.isSubmitting = true;
				
				// 构建与后端字段名匹配的提交数据
				const submitData = {
					username: this.formData.username,
					nickname: this.formData.nickname,
					phone: this.formData.phone, // 注意这里改为phone，与后端@RequestParam参数名完全一致
					gender: this.formData.gender,
					birthday: this.formData.birthday, // 日期格式会在API中处理
					city: this.formData.province + this.formData.city + this.formData.area,
					icon: this.formData.icon,
					job: this.formData.job,
					personalizedSignature: this.formData.signature // 注意：后端字段名可能是personalizedSignature
				};
				
				console.log('提交数据前:', submitData);
				
				// 提交表单
				updateMemberInfo(submitData).then(res => {
					console.log('提交结果:', res);
					if(res.errno === 0 || res.code === 200){
						// 重新获取用户信息
						this.loadUserInfo();
						
						// 显示确认对话框
						uni.showModal({
							title: '提示',
							content: '个人信息修改成功',
							confirmText: '确定',
							cancelText: '取消',
							success: function(result) {
								if (result.confirm) {
									// 点击确定，跳转到设置页面
									uni.navigateTo({
										url: '/pages/set/set'
									});
								}
								// 点击取消则留在当前页面，不需要额外操作
							}
						});
					} else {
						uni.showToast({
							icon: 'none',
							title: res.errmsg || res.message || '保存失败'
						});
					}
				}).catch(err => {
					console.error('保存失败', err);
					uni.showToast({
						icon: 'none',
						title: '保存失败，请重试'
					});
				}).finally(() => {
					this.isSubmitting = false;
				});
			},
			goToAvatarPage() {
				// 跳转到头像上传页面
				uni.navigateTo({
					url: '/pages/userinfo/avatar'
				});
			},
			// 选择生日日期
			bindDateChange(e) {
				// 获取选择器选择的日期
				const dateStr = e.detail.value;
				console.log('选择的日期:', dateStr);
				
				// 保存到表单
				this.formData.birthday = dateStr;
			},
			
			// 格式化日期为YYYY-MM-DD格式(兼容性处理)
			formatDate(date) {
				if (!date) return '';
				
				if (typeof date === 'string') {
					// 如果已经是正确格式的字符串，直接返回
					if (/^\d{4}-\d{2}-\d{2}$/.test(date)) {
						console.log('日期格式已是标准格式:', date);
						return date;
					}
					
					// 尝试转换为Date对象
					try {
						date = new Date(date);
					} catch (e) {
						console.error('日期转换错误:', e);
						return '';
					}
				}
				
				if (!(date instanceof Date) || isNaN(date.getTime())) {
					console.error('无效日期:', date);
					return '';
				}
				
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				
				const formattedDate = `${year}-${month}-${day}`;
				console.log('格式化日期结果:', formattedDate);
				return formattedDate;
			},
			// 获取性别显示文本
			getGenderText(gender) {
				const option = this.genderOptions.find(item => item.value === gender);
				return option ? option.text : '未知';
			}
		}
	}
</script>

<style lang="scss">
	page{
		background: $page-color-base;
	}
	.user-section{
		display:flex;
		align-items:center;
		justify-content: center;
		height: 460upx;
		padding: 40upx 30upx 0;
		position:relative;
		.bg{
			position:absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			filter: blur(1px);
			opacity: .7;
		}
		.portrait-box{
			width: 200upx;
			height: 200upx;
			border:6upx solid #fff;
			border-radius: 50%;
			position:relative;
			z-index: 2;
		}
		.portrait{
			position: relative;
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
		.yticon{
			position:absolute;
			line-height: 1;
			z-index: 5;
			font-size: 48upx;
			color: #fff;
			padding: 4upx 6upx;
			border-radius: 6upx;
			background: rgba(0,0,0,.4);
		}
		.pt-upload-btn{
			right: 0;
			bottom: 10upx;
		}
		.bg-upload-btn{
			right: 20upx;
			bottom: 16upx;
		}
	}
	
	.info-form {
		background-color: #fff;
		margin-top: 20upx;
		padding: 20upx 0;
	}
	
	.form-item {
		display: flex;
		align-items: center;
		padding: 30upx;
		border-bottom: 1upx solid #f6f6f6;
		
		.label {
			width: 180upx;
			font-size: 28upx;
			color: #606266;
		}
		
		.content {
			flex: 1;
			font-size: 28upx;
			color: #303133;
			
			input, .picker-content {
				height: 60upx;
				line-height: 60upx;
				font-size: 28upx;
				color: #303133;
			}
		}
		
		.yticon {
			font-size: 32upx;
			color: #909399;
			margin-left: 10upx;
		}
		
		&.textarea-item {
			align-items: flex-start;
			
			.content {
				height: 120upx;
				
				textarea {
					width: 100%;
					height: 100%;
					font-size: 28upx;
					color: #303133;
				}
			}
		}
	}
	
	.save-btn-box {
		margin: 60upx 30upx;
	}
	
	.save-btn {
		background-color: $uni-color-primary;
		color: #fff;
		border-radius: 50upx;
		height: 80upx;
		line-height: 80upx;
		font-size: 32upx;
	}
</style> 